import json

from django.http import *
from django.shortcuts import render

from .models import AddMeet
from django.db.models import Q
from django.contrib import messages
from django.core.paginator import Paginator
from django.core.cache import caches
import hashlib

from user.models import User

from department.models import Department


def select_menu(request):
    users = User.objects.all()

    lis = []
    for user in users:
        data = dict()
        data['id'] = user.id
        data['user_name'] = user.user_name
        data['role'] = user.role.name if user.role else None
        data['department'] = user.dept.title if user.dept else None
        data['telephone'] = user.telephone
        data['nickname'] = user.nickname
        data['email'] = user.email
        data['sex'] = user.sex
        data['last_login'] = user.last_login
        # 格式化时间的格式
        lis.append(data)
        # 前台传来的页数
    # page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    # page_limit = request.GET.get('limit')
    # 分页器进行分配
    # paginator = Paginator(lis, page_limit)
    # 前端传来页数的数据
    # data = paginator.page(page_index)
    # 放在一个列表里
    # user_info = [x for x in data]
    # # students.count()总数据量，layui的table模块要接受的格式
    # users = {"code": 0, "msg": "", "count": users.count(), "data": user_info}
    # 序列化 - python对象变为json字符串
    jsonStr = json.dumps(lis)
    # 反序列化 - json字符串变为python对象
    py_obj = json.loads(jsonStr)
    return JsonResponse(py_obj)


def list_meet(request):
    # 表格要展现的数据
    query = request.GET.get("keyword")
    if not query:
        print('a')
        meets = AddMeet.objects.all()
    else:
        print('b')
        meets = AddMeet.objects.filter(meetname__contains=query)
    # 处理成LayUi官方文档的格式
    lis = []
    for meet in meets:
        data = dict()
        data['id'] = meet.id
        data['meetnhuiyishiame'] = meet.meetname
        data['place'] = meet.place
        data['start_time'] = meet.start_time
        data['finish_time'] = meet.finish_time
        data['date'] = meet.date
        data['bossname'] = meet.bossname
        data['place'] = meet.place

        # 格式化时间的格式
        lis.append(data)
    #     # 前台传来的页数
    page_index = request.GET.get('page')
    # # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # # 前端传来页数的数据
    data = paginator.page(page_index)
    # # 放在一个列表里
    meet_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    users = {"code": 0, "msg": "", "count": meets.count(), "data": meet_info}
    return JsonResponse(meets)


def meet(request):
    return render(request, 'meet/operate_meet.html')


def operate_meet(request):
    # 表格要展现的数据
    query = request.GET.get("keyword")
    if not query:
        meets = AddMeet.objects.filter(add_user=request.session['user'])
    else:
        print('b')
        meets = AddMeet.objects.filter(meetname__contains=query, add_user=request.session['user'])
    # 处理成LayUi官方文档的格式
    uname = User.objects.get(id=request.session['user'].id).user_name

    lis = []
    for meet in meets:
        data = dict()
        data['id'] = meet.id
        data['meetname'] = meet.meetname
        data['place'] = meet.place
        data['start_time'] = meet.start_time
        data['finish_time'] = meet.finish_time
        data['date'] = meet.date

        # 格式化时间的格式
        lis.append(data)
    #     # 前台传来的页数
    page_index = request.GET.get('page')
    # # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # # 前端传来页数的数据
    data = paginator.page(page_index)
    # # 放在一个列表里
    meet_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    meets = {"code": 0, "msg": "", "count": meets.count(), "data": meet_info}
    return JsonResponse(meets)

    # return render(request,'meet/operate_meet.html')


def add_meet(request):
    if request.method == "GET":
        return render(request, 'meet/add_meet copy.html')
    elif request.method == "POST":
        print('收到post请求')
        json_str = request.body
        obj_str = json.loads(json_str)
        meet_content = obj_str["meet_content"]
        meet_personnel = obj_str['meet_personnel']
        # 获取会议时间

        date = meet_content["date"]

        start_time = meet_content["start_time"]

        finish_time = meet_content["finish_time"]
        # 获取内容
        meetname = meet_content["meetname"]
        place = meet_content["place"]
        add_user = request.session['user']
        meet=AddMeet.objects.create(date=date, start_time=start_time, finish_time=finish_time, meetname=meetname,
                               place=place, add_user=add_user, departement=request.session['user.department'])
        # 获取会议人员

        for id, person_name in meet_personnel.items():
            print('人员id:%s人员名称:%s' % (id, person_name))
            # 人员id:1人员名称:admin
            user = User.objects.get(id=id)
            meet.users.add(user)
            print('成功!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')

        return JsonResponse({"code": 200})


def edit_meet(request):
    if request.method == "GET":
        mid = request.GET.get('id')
        try:
            meet = AddMeet.objects.get(id=mid)
        except:
            return HttpResponseNotFound
        list_per = []
        for per in meet.users.all():
            list_per.append(per.id)
            mid = request.GET.get('id')
        return render(request, 'meet/edit_meet.html', locals())
    elif request.method == "POST":
        json_str = request.body
        obj_str = json.loads(json_str)
        meet_content = obj_str["meet_content"]
        meet_personnel = obj_str['meet_personnel']
        # 获取会议时间
        mid = meet_content['id']
        date = meet_content["date"]
        start_time = meet_content["start_time"]
        finish_time = meet_content["finish_time"]
        # 获取内容
        meetname = meet_content["meetname"]
        place = meet_content["place"]

        if not meetname:
            return JsonResponse({'state': 2})
            # messages.error('用户名或密码为空')

        if AddMeet.objects.filter(Q(meetname=meetname) & ~Q(id=mid)):
            return JsonResponse({'state': 0})
        try:
            meet = AddMeet.objects.get(id=mid)
        except:
            return JsonResponse({'state': 3})
        meet.meetname = meetname
        meet.place = place
        meet.date = date
        meet.start_time = start_time
        meet.finish_time = finish_time
        meet.departement = request.session['user.department']
        meet.users.clear()
        for id, person_name in meet_personnel.items():
            # 人员id:1人员名称:admin
            user = User.objects.get(id=id)
            meet.users.add(user)
        meet.save()
        return JsonResponse({'state': "1"})


def del_meet(request):
    mid = request.POST['id']
    meet = AddMeet.objects.get(id=mid)
    meet.delete()
    return JsonResponse({'state': "1"})


def transferdata(request):
    data = json.loads(request.body)
    print('>>>>>>>>>>>>>>>>--', data)
    return JsonResponse({'code': 200})


def get_report_transfer(request):
    '''

    参会人员处理成
    [
    {"value": "1", "title": "李白"}
    ,{"value": "2", "title": "杜甫"}
    ,{"value": "3", "title": "苏轼"}
    ]
    '''
    # 获取参会人员
    print("********************")
    print('收到了get请求')
    obj_meet_personnel = User.objects.all()
    if not obj_meet_personnel:
        return JsonResponse({'code': 30100, 'error': '没有参会人员'})
    # 处理数据
    personnels = []
    for meet_personnel in obj_meet_personnel:
        personnel = {}
        personnel['value'] = str(meet_personnel.id)
        personnel['title'] = meet_personnel.user_name
        personnels.append(personnel)
    # 获取当前用户名
    username = User.objects.get(id=request.session['user'].id).user_name
    # 向前端发送json数据
    return JsonResponse({"code": 200, 'data': personnels, 'publisher': username})


def my_meet(request):
    return render(request, 'meet/my_meet.html')


def detail_meet(request):
    mid = request.GET.get('id')
    try:
        meet = AddMeet.objects.get(id=mid)
    except:
        return HttpResponseNotFound
    list_per = []
    for per in meet.users.all():
        list_per.append(per.id)
        mid = request.GET.get('id')
    return render(request, 'meet/detail_meet.html', locals())


def my_meet_init(request):
    query = request.GET.get("keyword")
    user = request.session['user']
    if not query:
        meets = user.user_meets.all()
    else:
        meets = user.user_meets.all()
        meets = meets.filter(meetname__contains=query)
    # 处理成LayUi官方文档的格式

    lis = []
    for meet in meets:
        data = dict()
        data['id'] = meet.id
        data['meetname'] = meet.meetname
        data['place'] = meet.place
        data['start_time'] = meet.start_time
        data['finish_time'] = meet.finish_time
        data['date'] = meet.date
        data['add_user'] = meet.add_user.user_name

        # 格式化时间的格式
        lis.append(data)
    #     # 前台传来的页数
    page_index = request.GET.get('page')
    # # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # # 前端传来页数的数据
    data = paginator.page(page_index)
    # # 放在一个列表里
    meet_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    meets = {"code": 0, "msg": "", "count": meets.count(), "data": meet_info}
    return JsonResponse(meets)
